<template>
  <!-- 培训课题页面 -->
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button v-if="permission.trainingTopics_add" type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')"> 新 增 </el-button>
        <!--  -->
        <!-- &nbsp; -->
        <el-button v-if="permission.trainingTopics_del" type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          v-if="permission.trainingTopics_view"
          @click="openDialog('view', row)"
          type="text"
          size="small"
          plain
          class="el-icon-view"
          style="border: 0; background-color: transparent !important"
        >
          详情
        </el-button>

        <el-button
          v-if="permission.trainingTopics_edit"
          type="text"
          icon="el-icon-edit"
          size="small"
          plain
          @click="openDialog('edit', row)"
          style="border: 0; background-color: transparent !important"
          >编辑</el-button
        >
      </template>
      <template slot-scope="{ row }" slot="status">
        <el-tag>{{ row.status === 0 ? '否' : '是' }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="printLabelModal" width="75%" @close="clearFormData">
      <avue-form ref="printLabelForm" v-model="scopeDetail" v-if="printLabelModal" :option="scopeOption"> </avue-form>
      <el-tabs type="border-card" class="tabs-find">
        <el-tab-pane label="培训项列表">
          <avue-crud
            ref="crudItem"
            :option="trainingItemOption"
            :data="trainingItemList"
            @selection-change="selectionItemChange"
            @row-update="addUpdateItem"
            @row-save="rowSaveItem"
            @row-del="rowDelItem"
            @row-add="openAddItem"
          >
            <template slot="menuLeft" v-if="isShowBtn">
              <el-button type="primary" size="small" icon="el-icon-view" @click="rowSaveAllItem">保 存 </el-button>
              <el-button type="danger" size="small" icon="el-icon-delete" :disabled="itemIds.length > 0 ? false : true" @click="handleDeleteItem">删 除 </el-button>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-button class="btn-setting" v-if="isShowBtn" icon="el-icon-view" type="primary" size="small" @click="rowSave(scopeDetail)">保 存</el-button>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button size="small" type="primary" @click="onRejection">残忍拒收</el-button>
        <el-button size="small" @click="printLabelModal = false">关 闭</el-button> -->
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, addItem, removeItem } from '@/api/product/training-topics';
import { mapGetters } from 'vuex';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config';

export default {
  name: 'ProductTrainingTopics',
  mixins: [userConfig()],
  components: {
    userTableConfig
  },
  data() {
    return {
      pageCode: 'TRAING_TOPICS',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      // 选择培训项的列表
      selectionItemList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      // 培训课题的option
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,

        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        searchLabelWidth: 120,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        columnBtn: false,
        column: [
          {
            label: '培训课题',
            prop: 'subject',
            labelWidth: 120,
            search: true,
            searchOrder: 1,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '培训类型',
            prop: 'subjectType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=TRAINING_SUBJECT_TYPE',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入内容',
                trigger: 'blur'
              }
            ]
          },

          {
            label: '培训车间',
            prop: 'workshopName',
            // type: 'select',
            labelWidth: 120,
            // search: true,

            rules: [
              {
                required: true,
                message: '请选择车间',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '培训车间',
            minWidth: 120,
            prop: 'workshopId',
            search: true,
            searchOrder: 2,
            order: 3,
            type: 'select',
            hide: true,
            // type: 'number',
            // dataType: "number",
            dicUrl: '/api/mes-admin/workshop/key-value',
            props: {
              label: 'workshopName',
              value: 'workshopId'
            },
            rules: [
              {
                required: true,
                message: '请选择培训车间',
                trigger: 'change'
              }
            ]
          },
          {
            label: '制定人',
            prop: 'createUser',
            labelWidth: 120,
            type: 'search',
            disabled: true,
            placeholder: '请选择 制定人',
            order: 4,
            appendClick: () => {
              this.openWorkOrderNoModal();
            }
          },
          {
            label: '制定日期',
            prop: 'createTime',
            type: 'datetime'
            // hide: true,
            // display: false
          }
        ]
      },

      dialogTitle: '新增',
      printLabelModal: false,
      scopeDetail: {},
      // 新增的option
      scopeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '150',
        column: [
          {
            label: '培训课题',
            prop: 'subject',
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入内容',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '培训类型',
            prop: 'subjectType',
            type: 'select',
            span: 8,
            dicUrl: '/api/blade-system/dict/dictionary?code=TRAINING_SUBJECT_TYPE',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '培训车间',
            minWidth: 120,
            prop: 'workshopId',
            span: 8,
            type: 'select',
            // type: 'number',
            // dataType: "number",
            dicUrl: '/api/mes-admin/workshop/key-value',
            props: {
              label: 'workshopName',
              value: 'workshopId'
            },
            rules: [
              {
                required: true,
                message: '请选择培训车间',
                trigger: 'change'
              }
            ]
          },

          {
            label: '制定人',
            minWidth: 120,
            span: 8,
            prop: 'createUser',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入制定人',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '制定日期',
            prop: 'createTime',
            span: 8,
            disabled: true,
            type: 'datetime',
            rules: [
              {
                required: true,
                message: '请选择制定日期',
                trigger: 'change'
              }
            ]
          },
          {
            label: '课题说明',
            minWidth: 120,
            span: 8,
            prop: 'description'
          }
        ]
      },
      trainingItemList: [],
      // 培训项的option
      trainingItemOption: {
        addBtn: false,
        addRowBtn: true,
        cellBtn: true,
        // menuWidth: 250,
        selection: true,
        index: true,
        column: [
          {
            label: '培训项',
            prop: 'item',
            cell: true,
            rules: [
              {
                required: true,
                message: '请输入培训项',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      // 用于详情时候对操作按钮的隐藏
      isShowBtn: true
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.location_add, false),
        // viewBtn: this.vaildData(this.permission.location_view, false),
        // delBtn: this.vaildData(this.permission.location_delete, false),
        // editBtn: this.vaildData(this.permission.location_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    itemIds() {
      let ids = [];
      this.selectionItemList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    openDialog(type, view) {
      this.printLabelModal = true;

      if (type === 'add') {
        this.dialogTitle = '新增';
        this.isShowBtn = true;
        this.trainingItemOption.menu = true;
        this.trainingItemOption.selection = true;
        this.trainingItemOption.addRowBtn = true;
        // 清空一些数据
        // this.scopeDetail = {}
        // this.trainingItemList = []

        const userInfo = JSON.parse(localStorage.getItem('saber-userInfo'));

        if (userInfo && userInfo.content.user_name) {
          this.scopeDetail.createUser = userInfo.content.user_name;
        }
        this.scopeDetail.createTime = new Date();
      } else if (type === 'edit') {
        this.dialogTitle = '编辑';
        this.isShowBtn = true;
        this.trainingItemOption.menu = true;
        this.trainingItemOption.selection = true;
        this.trainingItemOption.addRowBtn = true;
      } else {
        this.dialogTitle = '详情';
        this.isShowBtn = false;
        this.trainingItemOption.menu = false;
        this.trainingItemOption.selection = false;
        this.trainingItemOption.addRowBtn = false;
      }
      if (view) {
        // this.scopeDetail = view
        this.getTrainingDetail(view.id);
      }
    },
    clearFormData() {
      this.scopeDetail = {};
      this.trainingItemList = [];
      this.printLabelModal = false;
    },
    getTrainingDetail(id) {
      getDetail(id).then((res) => {
        this.scopeDetail = res.data.data;
        this.trainingItemList = this._get(res.data.data, 'trainingItemList', []);
      });
    },
    openAddItem() {},
    // 整组保存
    rowSaveAllItem() {
      if (!this.scopeDetail.id) {
        this.$message.warning('请先保存培训课题后再操作！');
        return;
      }
      if (this.trainingItemList.length < 1) {
        this.$message.warning('请确保至少有一个培训项后再操作！');
        return;
      }
      let isSave = true,
        arrList = [];
      this.trainingItemList.forEach((row) => {
        if (!row.item) {
          isSave = false;
        }
        var obj = {
          subject: this.scopeDetail.subject,
          subjectId: this.scopeDetail.id,
          item: this._get(row, 'item', ''),
          id: this._get(row, 'id', ''),
          description: this._get(row, 'description', '')
        };
        arrList.push(obj);
      });
      if (!isSave) {
        this.$message.error('请确保所有参数培训项都有值！');
        return;
      }
      addItem(arrList).then(
        () => {
          this.getTrainingDetail(this.scopeDetail.id);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        },
        (error) => {
          this.getTrainingDetail(this.scopeDetail.id);
          window.console.log(error);
        }
      );
    },
    addUpdateItem(row, index, done, loading) {
      this.rowSaveItem(row, done, loading);
    },
    // 保存子项数据
    rowSaveItem(row, done, loading) {
      if (!this.scopeDetail.id) {
        this.$message.warning('请先保存培训课题后再操作！');
        return;
      }
      var obj = {
        subject: this.scopeDetail.subject,
        subjectId: this.scopeDetail.id,
        item: this._get(row, 'item', ''),
        id: this._get(row, 'id', ''),
        description: this._get(row, 'description', '')
      };

      addItem([obj]).then(
        () => {
          this.getTrainingDetail(this.scopeDetail.id);

          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          this.getTrainingDetail(this.scopeDetail.id);
          done();
          window.console.log(error);
        }
      );
    },
    rowSave(row, done, loading) {
      this.$refs.printLabelForm.validate((valid) => {
        if (valid) {
          var obj = {
            workshopId: this._get(row, 'workshopId', ''),
            description: this._get(row, 'description', ''),
            subject: this._get(row, 'subject', ''),
            id: this._get(row, 'id', ''),
            subjectType: this._get(row, 'subjectType', ''),
            createTime: this._get(row, 'createTime', ''),
            createUser: this._get(row, 'createUser', '')
          };
          add(obj).then(
            (res) => {
              this.scopeDetail.id = res.data.data;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        }
      });
    },
    rowDelItem(row) {
      this.$confirm('确定将数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeItem(row.id);
        })
        .then(() => {
          this.getTrainingDetail(this.scopeDetail.id);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDeleteItem() {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return removeItem(this.itemIds);
        })
        .then(() => {
          // this.getTrainingDetail(this.scopeDetail.id)
          this.trainingItemList.pop();
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },

    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionItemChange(list) {
      this.selectionItemList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getSelectData(code) {
      getSelectList(code)
        .then((res) => {
          this.selectData = res.data.data;
        })
        .catch((err) => {
          this.message(err);
        });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tabs-find {
  margin-bottom: 25px;
  position: relative;
  ::v-deep .el-tabs__content {
    position: static;
  }
  .btn-setting {
    position: absolute;
    right: 10px;
    top: 3px;
    z-index: 10;
  }
}
</style>
